﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SuperWebSocket;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using System.Threading;
using Newtonsoft.Json;

namespace WS.EKA.UI.Business
{
    public class WebSocketHelper
    {
        private static IBootstrap m_Bootstrap;
        private static WebSocketServer m_WebSocketServer;

        static WebSocketHelper()
        {
            m_Bootstrap = BootstrapFactory.CreateBootstrap();

            if (!m_Bootstrap.Initialize())
                return;

            var socketServer = m_Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("SuperWebSocket")) as WebSocketServer;

            socketServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(socketServer_NewMessageReceived);
            socketServer.NewSessionConnected += socketServer_NewSessionConnected;
            socketServer.SessionClosed += socketServer_SessionClosed;

            m_WebSocketServer = socketServer;

            m_Bootstrap.Start();
        }

        public static void ShutDownWebSocketServer()
        {
            if (m_WebSocketServer != null)
                m_WebSocketServer.Stop();
            if (m_Bootstrap != null)
                m_Bootstrap.Stop();

        }

        public static void StartWebSocketServer()
        {
        }

        /// <summary>
        ///这里收到的message来自后台推送的数据，
        ///我们需要将其推送到相同path下的客户端
        /// </summary>
        /// <param name="session"></param>
        /// <param name="message"></param>
        private static void socketServer_NewMessageReceived(WebSocketSession session, string message)
        {
            var clients = m_WebSocketServer.GetSessions(x => x.Path == session.Path);
            if (clients != null)
            {
                foreach (var s in clients)
                {
                    s.Send(message);
                }
            }
        }

        /// <summary>
        /// 客户端一旦连接成功，立即推送数据
        /// </summary>
        /// <param name="session"></param>
        private static void socketServer_NewSessionConnected(WebSocketSession session)
        {
            var obj = new
            {
                Name = "test case",
                Time = DateTime.Now
            };
            var msg = JsonConvert.SerializeObject(obj);
            session.Send(msg);
        }

        private static void socketServer_SessionClosed(WebSocketSession session, CloseReason reason)
        {
        }

    }
}